﻿using DevExpress.Utils;
using EyFramework.Common;
using EyFramework.Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using EyFramework.Common.Utils;
using ShuJuGj.Core.Service;
using ShuJuGj.Entity;
using ShuJuGj.Entity.Dto;
using ShuJuGj.Tj;

namespace ShuJuGj
{
    public partial class FrmTjTjbgsc : FrmDevBase
    {
        private ITjTjbgPdfService tjTjbgPdfService;

        public FrmTjTjbgsc()
        {
            InitializeComponent();
        }

        private void FrmNcov_Load(object sender, EventArgs e)
        {
            InitForm();
            de_start.Text = DateTime.Now.ToString("yyyy-MM-dd");
            de_end.Text = de_start.Text;
            btnQuery.Focus();
        }

        private void InitForm()
        {
            tjTjbgPdfService = Globals.GetService<ITjTjbgPdfService>();
            gvData.ShowRowNum();
            gcData.ShowContextMenu(this.components);//显示右键导出功能
            ToolStripMenuItem exportTxt = new ToolStripMenuItem();
            exportTxt.Name = "exportText";
            exportTxt.Size = new System.Drawing.Size(152, 22);
            exportTxt.Text = "导出Text(&T)";
            exportTxt.Tag = gcData;
            exportTxt.Click += ExportTxt_Click;
            gcData.ContextMenuStrip.Items.Add(exportTxt);
        }

        private void ExportTxt_Click(object sender, EventArgs e)
        {
            string fileName = Path.Combine(Globals.appConfigure.AppPath, "export.txt");
            if (FileUtil.FileIsExist(fileName))
            {
                FileUtil.DeleteFile(fileName);
            }
            else
            {
                FileUtil.CreateFile(fileName);
            }

            StringBuilder sbContent = new StringBuilder();
            for (int i = 0; i < gvData.RowCount; i++)
            {
                sbContent.AppendLine((gvData.GetRow(i) as TjTjbgjl).TIJIANBH);
            }
            File.WriteAllText(fileName, sbContent.ToString(), Encoding.GetEncoding("GB2312"));
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            ShowLoading();
            try
            {
                QueryData();
            }
            finally
            {
                CloseLoading();
            }
        }

        private void QueryData()
        {
            var queryParam = new TjbgPdfParam()
            {
                START_DT = de_start.DateTime.ToString("yyyy-MM-dd"),
                END_DT = de_end.DateTime.ToString("yyyy-MM-dd"),
                TIJIANBH = teTiJianBh.Text.Trim(),
                XINGMING = tePatnm.Text.Trim(),
                UPLOAD = cbeState.SelectedIndex
            };
            var bgDatas = tjTjbgPdfService.GetTjbgPdfList(queryParam);
            gcData.DataSource = bgDatas;
            DevPublic.SetBindGridControlView(gvData, true, true);
        }

        private void ribBtnEdit_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (gvData.FocusedRowHandle >= 0)
            {
                var tjTjbgjl = gvData.GetRow(gvData.FocusedRowHandle) as TjTjbgjl;
                if (e.Button.Index == 0)
                {
                    UploadPdf(tjTjbgjl);
                }
                else
                {
                    PreviewPdf(tjTjbgjl);
                }
            }
        }

        private void UploadPdf(TjTjbgjl tjTjbgjl)
        {
            //选择需要上传的PDF文件
            ofdPdf.ShowHelp = false;
            ofdPdf.InitialDirectory = Globals.appConfigure.AppPath;
            ofdPdf.Title = "选择体检PDF报告";
            ofdPdf.Multiselect = false;
            ofdPdf.Filter = "Pdf Files|*.pdf";
            if (ofdPdf.ShowDialog() == DialogResult.OK)
            {
                var filePath = System.IO.Path.GetFullPath(ofdPdf.FileName);
                tjTjbgPdfService.SaveTjbgPdf(tjTjbgjl, Globals.GetFileBase64Str(filePath));
            }
        }

        private void PreviewPdf(TjTjbgjl tjTjbgjl)
        {
            var tjbgPdf = tjTjbgPdfService.GetTjbgPdf(tjTjbgjl.TIJIANBH);
            if (tjbgPdf != null)
            {
                FrmReportView frmReportView = new FrmReportView(tjbgPdf);
                frmReportView.ShowDialog();
            }
            else
            {
                Globals.ShowTips("没有找到体检报告信息无法预览，请先上传！");
            }
        }

        private void btnPatchUpload_Click(object sender, EventArgs e)
        {
            if (fbdPdf.ShowDialog() == DialogResult.OK)
            {
                Func<object> action = () => BatchUploadPdf(fbdPdf.SelectedPath);
                bool result = bool.Parse(DoTaskAsync(action, true).ToString());
                if (result)
                {
                    Globals.ShowTips("体检报告PDF上传完毕");
                }
                else
                {
                    Globals.ShowError("体检报告PDF上传失败");
                }
            }
        }

        private bool BatchUploadPdf(string dirPath)
        {
            //第二种方法
            DirectoryInfo folder = new DirectoryInfo(dirPath);
            var files = folder.GetFiles("*.pdf");
            if (files.Length <= 0)
            {
                Globals.ShowWarning("当前目录下未找到任何pdf的文件！");
                return false;
            }

            //1、根据文件名称查询总检记录
            int gIndex = 1;
            foreach (FileInfo file in files)
            {
                ShowLoading(string.Format("正在上传第{0}/{1}条体检报告,请稍后...", gIndex++, files.Length));
                var tjbh = file.Name.Replace(file.Extension, "");
                TjTjbgjl tjTjbgjl = tjTjbgPdfService.GetTjbgjl(tjbh);
                if (tjTjbgjl != null)
                {
                    tjTjbgPdfService.SaveTjbgPdfSilent(tjTjbgjl, Globals.GetFileBase64Str(file.FullName));
                    File.Delete(file.FullName);
                }      
            }
            
            return true;
        }

        
    }
}